package com.groupbuying.payconsumer.mq;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.serializer.SerializerFeature;
import com.groupbuying.payconsumer.connector.OrderFeign;
import com.groupbuying.payconsumer.connector.SysconfigFeign;
import com.groupbuying.payconsumer.constants.BalancePayConstans;
import com.groupbuying.payconsumer.constants.PayInfoEnumConstants;
import com.groupbuying.payconsumer.domain.PayInfoDO;
import com.groupbuying.payconsumer.domain.PayOrderRelDO;
import com.groupbuying.payconsumer.service.PayInfoService;
import com.groupbuying.payconsumer.service.PayOrderRelService;
import com.groupbuying.payconsumer.utils.NumberValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *  支付中心余额消费者监听
 * @auther lisurilige
 * @date 2019/9/3
 */
@Component
public class BalancePayResult {
    Logger LOGGER = LoggerFactory.getLogger(BalancePayResult.class);

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private PayOrderRelService payOrderRelService;

    @Autowired
    private PayInfoService payInfoService;

    @Autowired
    private Producer producer;

    @Transactional(rollbackFor = Exception.class)
    public boolean dealResult(Map<String,Object> messageBody){

        String baseLog = "余额异步回执消费者，";

        LOGGER.info("{}=====开始执行回执信息处理:{}",baseLog,messageBody);

        //1.解析异步回执信息
        String balanceCode = messageBody.get("balanceCode") == null?null : messageBody.get("balanceCode").toString();
        String message = messageBody.get("message") == null?null : messageBody.get("message").toString();
        String payMoney = messageBody.get("payMoney") == null?null : messageBody.get("payMoney").toString();
        String orderNum = messageBody.get("orderNum") == null?null : messageBody.get("orderNum").toString();
        //判断金额是否合法
        if (!NumberValidator.isNumber(payMoney)){
            LOGGER.error("{}订单金额有误，订单号：{}，code：{}，msg：{}，payMoney：{}",
                    baseLog,orderNum,balanceCode,message,payMoney);
            return true;
        }

        //2. 获取订单信息
        //获取支付单与订单关联信息
        PayOrderRelDO payOrderRelDO = payOrderRelService.getByOutTradeNo(orderNum);
        //获取支付单信息
        PayInfoDO payInfoDO = payInfoService.get(payOrderRelDO.getId());

        if (payInfoDO == null){
            LOGGER.error("{}订单号查询订单不存在，订单号：{}，code：{}，msg：{}",
                    baseLog,orderNum,balanceCode,message);
            return true;
        }

        if (null == payInfoDO.getPayBalance()) {
            LOGGER.error("{}订单号查询订单金额为空，订单号：{}，code：{}，msg：{}",
                    baseLog,orderNum,balanceCode,message);
            return true;
        }

        //3.检查金额是否相等
        if (payInfoDO.getPayBalance().compareTo(new BigDecimal(payMoney)) != 0) {
            LOGGER.error("{}订单金额与回执支付信息金额不匹配，订单号：{}，code：{}，msg：{}，订单金额:{},回执金额:{}",
                    baseLog,orderNum,balanceCode,message,payInfoDO.getPayBalance(),payMoney);
            return true;
        }

        //4.查看状态是否是成功状态
        if (BalancePayConstans.BALANCE_PAY_SUCCESS.equals(balanceCode)){
            //查看订单是否为交易成功状态
            if (PayInfoEnumConstants.ENUM_PAYSTATE_SUCPAY.equals(payInfoDO.getPayState())){
                LOGGER.info("{}已经是交易成功状态，不做处理，第三方支付id：{}，code：{}，msg：{},订单金额:{}",
                        orderNum,balanceCode,message,payMoney);
                return true;
            }
            payInfoDO.setPayState(PayInfoEnumConstants.ENUM_PAYSTATE_SUCPAY);
            payInfoDO.setGmtModified(new Date());
            payInfoService.update(payInfoDO);
        } else {
            LOGGER.error("{}，回执信息处理，交易状态为未成功，订单号：{}，code：{}，msg：{}",
                    baseLog,orderNum,balanceCode,message);
            return true;
        }

        LOGGER.info("{}开始通知其他中心处理");
        //5. 获取订单信息
        Map orderMap = orderFeign.getOrderForPay(payOrderRelDO.getOrderId());

        //6. 订单是否属于够样优店
//        boolean curNotify = orderMap.get("orderId").toString().substring(4, 7).equals("000");
//        if (curNotify) {
//            //商户优惠规则  是否未删除和已存在
//            Map ruleMap = new HashMap();
//            ruleMap.put("ruleId", orderMap.get("opxRuleId"));
//            ruleMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
//            Map rulesMap = sysconfigFeign.getStoreOpexRule(ruleMap);
////            orderMap.putAll(rulesMap);
//            if (rulesMap == null) {
//                LOGGER.error("{}，回执信息处理，优惠规则已删除标志或者不存在，订单号：{}，code：{}，msg：{}",
//                        baseLog,orderNum,balanceCode,message);
//                return true;
//            }
//        }

        //7. 设置订单中心消息传递消息体
        Map<String, Object> orderParam = new HashMap<>();
        orderParam.put("orderId", orderMap.get("orderId"));
        //设置积分中心消息传递消息体
//        Map<String, Object> currencyParam = new HashMap<>();
//        if (curNotify) {
//            currencyParam.put("payId", payInfoDO.getId());
//            currencyParam.put("customerId", orderMap.get("customerId"));
//            currencyParam.put("consumptionAmount", orderMap.get("orderPrice"));
//            currencyParam.put("backCurrencyRatio", orderMap.get("backCurrencyRatio"));
//        }

        //8. 设置分账中心消息传递内容
        Map<String, Object> settleParam = new HashMap<>();
        settleParam.put("orderId", orderMap.get("orderId"));
        settleParam.put("outTradeNo", payOrderRelDO.getOutTradeNo());
        settleParam.put("ruleId", orderMap.get("opxRuleId"));
        settleParam.put("totalAmount", payInfoDO.getPayBalance());
        //收银台ID
        settleParam.put("counterId", orderMap.get("counterId"));
        //用户ID
        settleParam.put("customerId", orderMap.get("customerId"));
        //支付分账
        settleParam.put("settleType", "0");
        settleParam.put("payType", payInfoDO.getPayType());
        settleParam.put("payChannel", payInfoDO.getPayChannel());

        try {
            //9. 订单中心
            Message orderMessage = new Message(PayMQConfig.ORDER_TOPIC, PayMQConfig.ORDER_TAG_PAY,
                    JSON.toJSONString(orderParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(orderMessage);
            LOGGER.info("{}发送订单中心成功");
        } catch (Exception e) {
            LOGGER.error("{}第三方支付单号：{}，code：{}，错误提示：{}",baseLog,orderNum, balanceCode, "发送订单中心失败");
            e.printStackTrace();

        }
//        if (curNotify) {
//            try {
//                //10. 积分中心
//                Message currencyMessage = new Message(PayMQConfig.CURRENCY_TOPIC, PayMQConfig.CURRENCY_TAG_ADD,
//                        JSON.toJSONString(currencyParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
//                producer.send(currencyMessage);
//                LOGGER.info("{}发送积分中心成功");
//            } catch (Exception e) {
//                LOGGER.error("{}第三方支付单号：{}，code：{}，错误提示：{}",baseLog,balanceCode, balanceCode, "发送积分中心失败");
//                e.printStackTrace();
//            }
//        }

        try {
            //11. 分账中心
            Message settleMessage = new Message(PayMQConfig.SETTLE_TOPIC, PayMQConfig.SETTLE_TAG_SPLIT,
                    JSON.toJSONString(settleParam, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(settleMessage);
            LOGGER.info("{}发送分账中心成功");
        } catch (Exception e) {
            LOGGER.error("{}第三方支付单号：{}，code：{}，错误提示：{}",baseLog,balanceCode, balanceCode, "发送分账中心失败");
            e.printStackTrace();
            //发送不成功的话，稍后重试
        }
        return true;
    }


}
